const app = getApp()
const Constants = require('../../utils/constants');
const Api = require('../../utils/api.js');
const Rest = require('../../utils/rest');
const util = require('../../utils/util.js');
const { IsHaveStr,IsNotEmpty } = require('../../utils/util.js');
let setinad;
Page({
    data: {
        logo: '',
        background: '',
        top_background: '',
        //顶部导航
        topNav: [{
            id: 0,
            name: '首页'
        }],
        currentTab: 0, //预设当前项的值

        //幻灯片
        slide: [],

        //图片导航
        iconNav: [],
        
        //公告
        iconNac: [],

        //活动轮播
        iconhdlb: [],
       
        //弹窗广告
        tcad: [],
        tcad1:[],

        //热门文章
        hot: [],

        //热门tab
        postsLast: [],
        loaddingLast: false,
        pullUpOnLast: true,

        //其他tab
        posts: [],
        loadding: false,
        pullUpOn: true,
        //列表模式
        listMode: 3,
        state: true,
        // 获取首页数据
       
    },
    //弹窗广告开始
   // 点击隐藏弹出蒙版
  hiddenMsak() {
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation;
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    //首先获取是否执行过
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showAd: true
      })
    }.bind(this), 200)
  },
//首页弹窗
    onLoad: async function (options) {
        //加载topNav，也就是顶部分类导航栏
        let that = this;
      await  util.getshare(that);
      await  Rest.get(Api.JIANGQIE_SETTING_HOME).then(res => {
            console.log(res.data)
            that.setData({
                //topNav: that.data.topNav.concat(res.data.top_nav)
            })
        })
        
      await that.init();
        let today = wx.getStorageSync('today')
        console.log(today)
        if (!today) {
            wx.setStorageSync("today", new Date().toLocaleDateString());
            that.setData({
                tcad1:that.data.tcad
            })
        }else{
            if (today != new Date().toLocaleDateString()) {
                that.setData({
                    tcad1:that.data.tcad
                })
            }else{
                that.setData({
                    tcad1:[]
                })
            }
        }
        /*波浪*/this.wave = this.selectComponent("#wave");
        this.wave.__hideInfo()/*玻璃效果*/
    },
onPullDownRefresh() {
    wx.stopPullDownRefresh()
    this.setData({
        state: false
    })
    this.init();
},
    init: async function () {
        let that = this;
        let state = that.data.state;
        //获取配置
      await  Rest.get(Api.JIANGQIE_SETTING_HOME).then(res => {
            let logo = '../../images/logo-index.png';
            if (res.data.logo && res.data.logo.length > 0) {
                logo = res.data.logo;
                
            }
            if (state) {
                that.setData({
                    topNav: that.data.topNav.concat(res.data.top_nav),
                });
            }
            that.setData({
                logo: logo,
                slide: res.data.slide,
                iconNav: res.data.icon_nav,
                iconNac: res.data.icon_nac,
                iconhdlb: res.data.icon_hdlb,
                tcad: res.data.tcad,
                actives: res.data.actives,
                hot: res.data.hot,
                listMode: res.data.list_mode,
                top_background: res.data.top_background,
                background: (res.data.slide && res.data.slide.length>0)?Api.JIANGQIE_BG_INDEX:'',
            });

            if (res.data.title && res.data.title.length > 0) {
                getApp().appName = res.data.title;
            }
        })

        //加载文章
     await  this.loadPostLast(true);
    },

    onReachBottom: function () {
        if (this.data.currentTab == 0) {
            if (!this.data.pullUpOnLast) {
                return;
            }

            this.loadPostLast(false);
        } else {
            if (!this.data.pullUpOn) {
                return;
            }

            this.loadPost(false);
        }
    },
//top图标默认显示
    top: function(){
        this.setData({
        top_background: '../../images/top-fill.png'
        }) 
       },
//获取滚动条当前位置
    onPageScroll: function (e) {
       
        if (e.scrollTop > 100) {
          this.setData({
            floorstatus: true
          });
        } else {
          this.setData({
            floorstatus: false
          });
        }
      },
      goTop: function (e) {  
        if (wx.pageScrollTo) {
          wx.pageScrollTo({
            scrollTop: 0
          })
        } else {
          wx.showModal({
          })
        }
      },
      onShareAppMessage: function () {
        var that = this;
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
        return {
            title: that.data.shares.share_title,
            imageUrl: that.data.shares.share_image,
        }
    },
    //转发朋友圈
    onShareTimeline: function () {
        var that = this;
        return {
            title: that.data.shares.share_title,
            path: 'pages/index/index',
            imageUrl: that.data.shares.share_image,
        }
    },
    // 收藏
    onAddToFavorites:function(){
        var that = this;
        return {
            title: that.data.shares.share_title,
            path: 'pages/index/index',
            imageUrl: that.data.shares.share_image,
        }
    },


    //nav start----
    handlerSearchClick: function (e) {
        wx.navigateTo({
            url: '/pages/search/search'
        })
    },
    //nav end ----
       //nav start----
       news: function (e) {
        wx.navigateTo({
            url: '/pages/news/news'
        })
    },
    //nav end ----

    //slide start----
    handlerSlideChange: function (e) {
        this.setData({
            current: e.detail.current
        })
    },
    //slide end----

    //tab -- start
    swichNav: function (e) {
        let cur = e.currentTarget.dataset.current;
        if (this.data.currentTab == cur) {
            return false;
        }

        this.setData({
            background: (cur==0 && this.data.slide && this.data.slide.length>0)?Api.JIANGQIE_BG_INDEX:'',
            currentTab: cur
        })

        if (cur !== 0) {
            this.loadPost(true);
        }
    },

    handlerTabMoreClick: function (e) {
        wx.switchTab({
          url: '/pages/categories/categories',
        })
    },
    //tab -- end

    handlerIconNavClick: function(e) {
        let link = e.currentTarget.dataset.link;
        this.openLink(link);
    },
    
    handlericonNacClick: function(e) {
        let link = e.currentTarget.dataset.link;
        this.openLink(link);
    },

    handlerActiveClick: function(e) {
        let link = e.currentTarget.dataset.link;
        this.openLink(link);
    },

    handlerArticleClick: function (e) {
        let post_id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '/pages/article/article?post_id=' + post_id
        })
    },
/*公告h5跳转*/ 
viewUrl(res){  //公告内容中，跳转的外链接
    let link =res.currentTarget.dataset.link;
    console.info(link)
    if (res &&IsNotEmpty(link)) {
        let isAddr =IsHaveStr(link,"http");
        /*console.info(link)*/
            wx.navigateTo({
                url:isAddr? '/pages/webview/webview?href=' + link:link
              }) 
    }
    else if(!IsNotEmpty(link)){
        wx.showToast({
            title: '取消或未配置',
            image: '../../images/lj.png',
          })
    }
  },
/*公告结束*/ 
    //加载数据
    loadPostLast: function (refresh) {
        let that = this;

        that.setData({
            loaddingLast: true
        });

        let offset = 0;
        if (!refresh) {
            offset = that.data.postsLast.length;
        }

        Rest.get(Api.JIANGQIE_POSTS_LAST, {
            'offset': offset
        }).then(res => {
            that.setData({
                loaddingLast: false,
                postsLast: refresh ? res.data : that.data.postsLast.concat(res.data),
                pullUpOnLast: res.data.length >= Constants.JQ_PER_PAGE_COUNT
            });
        })
    },

    loadPost: function (refresh) {
        let that = this;

        that.setData({
            loadding: true
        });

        let offset = 0;
        if (!refresh) {
            offset = that.data.posts.length;
        }

        Rest.get(Api.JIANGQIE_POSTS_CATEGORY, {
            'offset': offset,
            'cat_id': that.data.topNav[that.data.currentTab].id
        }).then(res => {
            that.setData({
                loadding: false,
                posts: refresh ? res.data : that.data.posts.concat(res.data),
                pullUpOn: res.data.length >= Constants.JQ_PER_PAGE_COUNT
            });
        })
    },
/*无链接或路径提示*/
    openLink: function(link) {
        if(link.startsWith('/pages')) {
            wx.navigateTo({
              url: link,
            })
        } else {
            wx.navigateToMiniProgram({
                appId: link,
                fail: res => {
                    wx.showToast({
                      title: '取消或未配置',
                      image: '../../images/lj.png',
                    })
                } 
            })
        }
    }
})
